package fr.unice.polytech.chord.samples.commands;

import fr.unice.polytech.chord.core.Entry;
import fr.unice.polytech.chord.core.Key;
import fr.unice.polytech.chord.samples.managers.Manager;

/**
 * @author Laurent Pellegrino
 * 
 * @version 10/30/2009
 */
public class GetCommand extends Command {

	/**
	 * Constructor.
	 * 
	 * @param manager
	 *            the manager that will execute this command.
	 */
	public GetCommand(Manager manager) {
		super(manager, "Retrieves a value associated to a key", new String[] {
				"get", "g" }, new String[] { "key" });
	}

	/**
	 * {@inheritDoc}
	 */
	public void execute(String... args) {
		if (args.length == 1) {
			Key keyToFind = null;
			try {
				keyToFind = new Key(Integer.parseInt(args[0]));
			} catch (Exception e) {
				super.printInfo("Key argument must be a number");
				return;
			}

			Entry<String> result = super.getManager().getTracker()
					.getRandomPeer().get(keyToFind);

			if (result == null) {
				super.printInfo("Nobody on the overlay contains the key");
			} else {
				super.printInfo("Key " + keyToFind
						+ " has been found and associated value is '" + result
						+ "'");
			}
		} else {
			super
					.printInfo("Get operation must have one argument which is the key to find");
		}
	}
}
